package com.lychee.lycheeapp.ui_user;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lychee.lycheeapp.IUrlInterface;
import com.lychee.lycheeapp.R;
import com.lychee.lycheeapp.entity.BaseResultEntity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {

    @BindView(R.id.mEditUsername)
    EditText mEditUsername;
    @BindView(R.id.mEditPassword)
    EditText mEditPassword;
    @BindView(R.id.mTvLogin)
    TextView mTvLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.mTvLogin)
    public void onViewClicked() {
        String userName = mEditUsername.getText().toString();
        String password = mEditPassword.getText().toString();
        if (TextUtils.isEmpty(userName) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "信息不全", Toast.LENGTH_SHORT).show();
            return;
        }
        OkHttpUtils.post().url(IUrlInterface.baseUrl + IUrlInterface.userLogin)
                .addParams("userName", userName)
                .addParams("password", password)
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                Toast.makeText(LoginActivity.this, response, Toast.LENGTH_SHORT).show();
                BaseResultEntity<String> baseResultEntity = new Gson().fromJson(response, BaseResultEntity.class);
                SharedPreferences preferences = LoginActivity.this.getSharedPreferences("Token", MODE_PRIVATE);
                SharedPreferences.Editor edit = preferences.edit();
                edit.putString("TokenID", baseResultEntity.getData());
                edit.apply();
            }
        });
    }
}
